/**
 * 创建人:  @author huangpeng    
 * 创建时间:  2022年06月05日 17:34
 * 项目名称:  lemon-blog-cloud
 * 文件名称:  MinioClientUtils
 * 文件描述:  @Description: minio对象存储工具类
 * 公司名称:  HBlog
 *
 * All rights Reserved, Designed By HBlog 
 * @Copyright: 2021-2022
 *
 */
package com.lemon.file.utils;

import com.alibaba.fastjson.JSONObject;
import com.lemon.common.core.constant.CacheConstants;
import com.lemon.common.core.constant.ConfigConstants;
import com.lemon.common.core.exception.ServiceException;
import com.lemon.common.redis.service.RedisService;
import com.lemon.file.config.MinioConfig;
import com.lemon.file.domain.BiElements;
import com.lemon.file.domain.vo.FileVo;
import com.lemon.file.domain.vo.FolderVo;
import com.lemon.file.mapper.BiElementsMapper;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * 包名称：com.lemon.file.utils
 * 类名称：MinioClientUtils
 * 类描述：minio对象存储工具类
 * 创建人：@author huangpeng 
 * 创建时间：2022年06月05日 17:34
 */
@Component
public class MinioClientUtils {

    private final Logger log = LoggerFactory.getLogger(MinioClientUtils.class);

    @Autowired
    private BiElementsMapper biElementsMapper;

    @Autowired
    private RedisService redisService;

    private MinioClient minioClient;

    private final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;

    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return boolean
     */
    public boolean bucketExists(String bucketName) throws Exception {
        boolean flag = false;
        flag = getMinioClient().bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        return flag;
    }

    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名称
     */
    public boolean makeBucket(String bucketName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (!flag) {
            getMinioClient().makeBucket(
                    MakeBucketArgs.builder()
                            .bucket(bucketName)
                            .build());
            return true;
        } else {
            return false;
        }
    }

    /**
     * 列出所有存储桶名称
     *
     * @return List<String>
     */
    public List<String> listBucketNames() throws Exception {
        List<Bucket> bucketList = listBuckets();
        List<String> bucketListName = new ArrayList<>();
        for (Bucket bucket : bucketList) {
            bucketListName.add(bucket.name());
        }
        return bucketListName;
    }

    /**
     * 列出所有存储桶
     *
     * @return List<Bucket>
     */
    public List<Bucket> listBuckets() throws Exception {
        return getMinioClient().listBuckets();
    }

    /**
     * 删除存储桶
     *
     * @param bucketName 存储桶名称
     * @return boolean
     */
    public boolean removeBucket(String bucketName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myObjects = listObjects(bucketName);
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                // 有对象文件，则删除失败
                if (item.size() > 0) {
                    return false;
                }
            }
            // 删除存储桶，注意，只有存储桶为空时才能删除成功。
            getMinioClient().removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
            flag = bucketExists(bucketName);
            return !flag;

        }
        return false;
    }

    /**
     * 列出存储桶中的所有对象名称
     *
     * @param bucketName 存储桶名称
     * @return List<String>
     */
    public List<String> listObjectNames(String bucketName) throws Exception {
        List<String> listObjectNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myObjects = listObjects(bucketName);
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                listObjectNames.add(item.objectName());
            }
        }
        return listObjectNames;
    }

    /**
     * 列出存储桶中的所有对象
     *
     * @param bucketName 存储桶名称
     * @return Iterable<Result<Item>>
     */
    public Iterable<Result<Item>> listObjects(String bucketName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            return getMinioClient().listObjects( ListObjectsArgs.builder().bucket(bucketName).build());
        }
        return null;
    }

    /**
     * 通过文件上传到对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param fileName   File name
     * @return boolean
     */
    public boolean uploadObject(String bucketName, String objectName, String fileName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            getMinioClient().uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(bucketName).object(objectName).filename(fileName).build());
            StatObjectResponse statObject = statObject(bucketName, objectName);
            return statObject != null && statObject.size() > 0;
        }
        return false;

    }

    /**
     * 文件上传
     *
     * @param bucketName 存储捅名称
     * @param multipartFile 文件
     * @param objectName   文件名, 包含路径
     */
    public void putObject(String bucketName, MultipartFile multipartFile, String objectName) throws Exception {
        getMinioClient().putObject(
                PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                                multipartFile.getInputStream(), multipartFile.getSize(), -1).contentType(multipartFile.getContentType())
                        .build());
    }

    /**
     * 通过InputStream上传对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 文件名, 包含路径
     * @param inputStream     要上传的流
     * @param contentType 上传的文件类型 例如 video/mp4  image/jpg
     * @return boolean
     */
    public boolean putObject(String bucketName, String objectName, InputStream inputStream, String contentType) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            getMinioClient().putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                            //不清楚文件的大小时，可以传-1，10485760。如果知道大小也可以传入size，partsize。
                            inputStream,  -1, 10485760)
                    .contentType(contentType)
                    .build());
            StatObjectResponse statObject = statObject(bucketName, objectName);
            return statObject != null && statObject.size() > 0;
        }
        return false;
    }

    /**
     * 以流的形式获取一个文件对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return InputStream
     */
    public InputStream getObject(String bucketName, String objectName) throws Exception {
        
        boolean flag = bucketExists(bucketName);
        if (flag) {
            StatObjectResponse statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.size() > 0) {
                InputStream stream = getMinioClient().getObject( GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
                return stream;
            }
        }
        return null;
    }

    /**
     * 以流的形式获取一个文件对象（断点下载）
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param offset     起始字节的位置
     * @param length     要读取的长度 (可选，如果无值则代表读到文件结尾)
     * @return InputStream
     */
    public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            StatObjectResponse statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.size() > 0) {
                InputStream stream = getMinioClient().getObject(  GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .offset(1024L)
                        .length(4096L)
                        .build());
                return stream;
            }
        }
        return null;
    }

    /**
     * 下载并将文件保存到本地
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param fileName   File name
     * @return boolean
     */
    public boolean downloadObject(String bucketName, String objectName, String fileName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            StatObjectResponse statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.size() > 0) {
                getMinioClient().downloadObject(DownloadObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .filename(fileName)
                        .build());
                return true;
            }
        }
        return false;
    }

    /**
     * 删除一个对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     */
    public boolean removeObject(String bucketName, String objectName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            getMinioClient().removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
            return true;
        }
        return false;
    }

    /**
     * 删除指定桶的多个文件对象,返回删除错误的对象列表，全部删除成功，返回空列表
     *
     * @param bucketName  存储桶名称
     * @param objectNames 含有要删除的多个object名称的迭代器对象，带路径的不要文件后缀的文件名
     * @return List<String> 删除失败的文件
     * eg:
     * List<DeleteObject> objects = new LinkedList<>();
     * objects.add(new DeleteObject("my-objectname1"));
     * objects.add(new DeleteObject("my-objectname2"));
     * objects.add(new DeleteObject("my-objectname3"));
     */
    public List<String> removeObjects(String bucketName, List<DeleteObject> objectNames) throws Exception {
        List<String> deleteErrorNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<DeleteError>> results = getMinioClient().removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(objectNames).build());
            for (Result<DeleteError> result : results) {
                DeleteError error = result.get();
                log.error("文件删除失败! errorMsg = {}", error.message());
                deleteErrorNames.add(error.objectName());
            }
        }
        return deleteErrorNames;
    }

    /**
     * 生成一个给HTTP GET请求用的presigned URL。
     * 浏览器/移动端的客户端可以用这个URL进行下载，即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间，默认值是7天。
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param expires    失效时间（以秒为单位），默认是7天，不得大于七天
     * @return String
     */
    public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws Exception {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
                try {
                    throw new MinioException("过期时间必须在1到" + DEFAULT_EXPIRY_TIME + "之间！");
                } catch (Exception e) {
                    log.info(e.getMessage());
                    e.printStackTrace();
                }
            }
            url = getMinioClient().getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(bucketName)
                    .object(objectName)
                    .expiry(expires)
                    // .expiry(24 * 60 * 60)//用秒来计算一天时间有效期
                    // .expiry(1, TimeUnit.DAYS)//按天传参
                    // .expiry(1, TimeUnit.HOURS)//按小时传参数
                    .build());
        }
        return url;
    }

    /**
     * 生成一个给HTTP PUT请求用的presigned URL。
     * 浏览器/移动端的客户端可以用这个URL进行上传，即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间，默认值是7天。
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param expires    失效时间（以秒为单位），默认是7天，不得大于七天
     * @return String
     */
    public String presignedPutObject(String bucketName, String objectName, Integer expires) throws Exception {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
                try {
                    throw new MinioException("过期时间必须在1到" + DEFAULT_EXPIRY_TIME + "之间！");
                } catch (Exception e) {
                    log.info(e.getMessage());
                    e.printStackTrace();
                }
            }
            url = getMinioClient().getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.PUT)
                    .bucket(bucketName)
                    .object(objectName)
                    .expiry(expires)//动态参数
                    // .expiry(24 * 60 * 60)//用秒来计算一天时间有效期
                    // .expiry(1, TimeUnit.DAYS)//按天传参
                    // .expiry(1, TimeUnit.HOURS)//按小时传参数
                    .build());
        }
        return url;
    }

    /**
     * 获取对象的元数据
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return StatObjectResponse
     */
    public StatObjectResponse statObject(String bucketName, String objectName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            StatObjectResponse statObject = null;
            statObject = getMinioClient().statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
            return statObject;
        }
        return null;
    }

    /**
     * 文件访问路径
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param expires 过期时间，单位秒
     * @return String
     */
    public String getObjectUrl(String bucketName, String objectName, int expires) throws Exception {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            url = getMinioClient().getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .bucket(bucketName)
                            .method(Method.GET)
                            .object(objectName)
                            .expiry(expires)
                            .build()
            );
        }
        return url;
    }

    /**
     * 获取永久文件链接
     * @Title: getObjectUrl
     * @Description: 获取永久文件链接
     * @param bucketName
     * @param objectName
     * @return: String
     * @throws:
     * @author: huangpeng
     * @Date: 2022/7/3 19:59
     */
    public String getObjectUrl(String bucketName, String objectName) throws Exception {
        boolean flag = bucketExists(bucketName);
        MinioConfig minioConfig = getMinioConfig();
        String url = "";
        if (flag) {
            url = minioConfig.getUrl().concat("/").concat(bucketName).concat("/").concat(objectName);
        }
        return url;
    }

    /**
     * 浏览器文件下载
     * @Title: downloadFile
     * @Description: 浏览器文件下载
     * @param bucketName
     * @param fileName
     * @param originalName
     * @param response
     * @return: void
     * @throws:
     * @author: huangpeng
     * @Date: 2022/6/5 20:53
     */
    public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {
        try {
            InputStream file = getMinioClient().getObject(GetObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .build());
            String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
            if (StringUtils.isNotEmpty(originalName)) {
                fileName = originalName;
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            ServletOutputStream servletOutputStream = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = file.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
            file.close();
            servletOutputStream.close();
        } catch (ErrorResponseException e) {
            log.error("ErrorResponseException",e);
        } catch (Exception e) {
            log.error("Exception",e);
        }
    }

    /**
     * 获取指定文件桶下的所有文件
     * @Title: listAll
     * @Description: 获取指定文件桶下的所有文件
     * @param bucket 桶
     * @return: List<FileVo>
     * @throws:
     * @author: huangpeng
     * @Date: 2022/6/5 2:27
     */
    public FolderVo listAll(String bucket) {
        FolderVo folderRoot = new FolderVo();
        folderRoot.setFolderName(bucket.concat("/"));
        List<FileVo> fileList = new ArrayList<>();
        List<FolderVo> folderList = new ArrayList<>();
        try {
            ListObjectsArgs args = ListObjectsArgs.builder().bucket(bucket).build();
            // 得到bucket下的⽂件
            Iterable<Result<Item>> results = getMinioClient().listObjects(args);
            // 循环遍历获取每⼀个⽂件对象
            results.forEach(g -> {
                try {
                    if (g.get().isDir()) {
                        FolderVo folder = new FolderVo();
                        String folderName = g.get().objectName();
                        folder.setFolderName(folderName);
                        List<Item> itemList = getAllObjectsByPrefix(bucket, g.get().objectName(), true);
                        List<FileVo> childList = new ArrayList<>();
                        itemList.forEach(e -> {
                            System.out.println(e.isDir() ? "文件夹" : "文件");
                            handleFile(childList, e, folderName, bucket);
                        });
                        folder.setFileList(childList);
                        folderList.add(folder);
                    } else {
                        handleFile(fileList, g.get(), bucket, bucket);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            folderRoot.setChildFolder(folderList);
            folderRoot.setFileList(fileList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return folderRoot;
    }

    /**
     * LocalDateTime转换为Date
     * @param localDateTime
     */
    public Date localDateTime2Date(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);
        Date date = Date.from(zdt.toInstant());
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 由于获取的时间存在时间差，我这⾥⼿动加上16⼩时
        cal.add(Calendar.HOUR_OF_DAY, 16);
        date = cal.getTime();
        return date;
    }

    /**
     * 根据文件前缀查询文件
     * @param bucketName 存储桶
     * @param prefix 前缀
     * @param recursive 是否使用递归查询
     * @return MinioItem 列表
     * @throws Exception
     */
    public List<Item> getAllObjectsByPrefix(String bucketName,
                                                   String prefix,
                                                   boolean recursive) throws Exception {
        List<Item> list = new ArrayList<>();
        Iterable<Result<Item>> objectsIterator = getMinioClient().listObjects(
                ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
        if (objectsIterator != null) {
            for (Result<Item> o : objectsIterator) {
                Item item = o.get();
                list.add(item);
            }
        }
        return list;
    }

    /**
     * 文件处理
     * @Title: handleFile
     * @Description: 文件处理
     * @param fileVos
     * @param g
     * @param folderName
     * @param bucket
     * @return: void
     * @throws:
     * @author: huangpeng
     * @Date: 2022/6/5 13:54
     */
    private void handleFile(List<FileVo> fileVos, Item g, String folderName, String bucket) {
        MinioConfig minioConfig = getMinioConfig();
        DecimalFormat df = new DecimalFormat("0.00");
        FileVo fileVo = new FileVo();
        // ⽂件夹名称
        fileVo.setFilePath(folderName);
        fileVo.setFileName(g.objectName().substring(g.objectName().lastIndexOf("/") + 1, g.objectName().length()));
        fileVo.setOriginFileName(g.objectName());
        fileVo.setUrl(minioConfig.getUrl().concat("/").concat(bucket).concat("/").concat(g.objectName()));
        // ⽂件名称
        // ⽂件上传时间
        fileVo.setUpdateTime(localDateTime2Date(g.lastModified().toLocalDateTime()));
        long size = g.size();
        if (size > (1024 * 1024)) {
            // ⽂件⼤⼩，如果超过1M，则把单位换成MB
            fileVo.setFileSize(df.format(((double) size / 1024 / 1024)) + "MB");
        } else if (size > 1024) {
            // ⽂件⼤⼩，如果没超过1M但是超过1000字节，则把单位换成KB
            fileVo.setFileSize(df.format(((double) size / 1024)) + "KB");
        } else {
            // // ⽂件⼤⼩，如果没超过1000字节，则把单位换成bytes
            fileVo.setFileSize(size + "bytes");
        }
        fileVos.add(fileVo);
    }

    /**
     * 获取minio配置信息
     * @Title: getMinioConfig
     * @Description: 获取minio配置信息
     * @return: MinioConfig
     * @throws:
     * @author: huangpeng
     * @Date: 2023/4/10 20:58
     */
    private MinioConfig getMinioConfig() {
        MinioConfig minioConfig;
        try {
            Map<String, Object> configMap = new HashMap<>();
            String cacheKey = ConfigConstants.MINIO_CONFIG.toLowerCase() + CacheConstants.KEY_SUFFIX;
            if (redisService.hasKey(cacheKey)) {
                configMap = redisService.getCacheMap(cacheKey);
            } else {
                BiElements element = new BiElements();
                element.setFunctionCode(ConfigConstants.MINIO_CONFIG);
                List<BiElements> elementsList = biElementsMapper.selectBiElementsList(element);
                for (BiElements elementInfo : elementsList) {
                    configMap.put(elementInfo.getElementCode(), elementInfo.getElementValue());
                }
                redisService.setCacheMap(cacheKey, configMap);
            }
            minioConfig = JSONObject.parseObject(JSONObject.toJSONString(configMap), MinioConfig.class);
        } catch (Exception e) {
            throw new ServiceException("获取minio配置信息出错，请检查是否在要素配置中配置minio的配置信息");
        }
        return minioConfig;
    }

    /**
     * 获取MinioClient
     * @Title: getMinioClient
     * @Description: 获取MinioClient
     * @return: MinioClient
     * @throws:
     * @author: huangpeng
     * @Date: 2023/4/10 20:58
     */
    private MinioClient getMinioClient() {
        MinioConfig minioConfig = getMinioConfig();
        return MinioClient.builder().endpoint(minioConfig.getUrl()).credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey()).build();
    }
}
